/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.platform.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wealth.member.entity.Membership;
import com.wealth.member.repository.MembershipDao;
import com.wealth.platform.entity.Account;
import com.wealth.platform.repository.AccountDao;
import com.wealth.platform.service.IAccountService;
import com.wealth.system.entity.Corporation;

import iaas.service.impl.BaseServiceImpl;
import iaas.utils.ResultObject;

/**
 * @author xingfan
 */
@Component
public class AccountServiceImpl extends BaseServiceImpl<Account> implements IAccountService{
	
	Logger logger = Logger.getLogger(AccountServiceImpl.class);

	@Autowired
	private AccountDao accountDao;
	@Autowired
	private MembershipDao membershipDao;

	/**
	 * 读取文件
	 * create by chan on 2016-09-08
	 * 
	 * Tip:
	 * 物理行数 sheet.getPhysicalNumberOfRows();  如：1,2,3,5行有数据，有效行数为4，这里不要使用它，会导致遍历缺失或出错
	 * 最后一行的下标 sheet.getLastRowNum();        如：有10行，下标为9
	 * 最后一列的位置 row.getLastCellNum();            如：有5列，  返回值为5   MDZZ?待再次确认
	 */
	@Override
	public boolean importFile(MultipartFile file,Long corpid) throws Exception {
	
		try {
			/** -------- 读取文件 -------- */
			//第一种方式，根据后缀名使用不同的实现类
			//将excel文件转换为输入流
//			workbook = new HSSFWorkbook();
//			if(file.getName().indexOf(".xlsx")>-1){//2007格式XSSF
//				workbook = new XSSFWorkbook();
//			}

			//第二种方式
			//工作簿
			Workbook workbook = WorkbookFactory.create(file.getInputStream());		
			//工作表
			Sheet sheet =workbook.getSheetAt(0); 					
			//总行
			int rows = sheet.getLastRowNum();																
			logger.info("--> poi read : rows="+rows);
			//遍历行, r=0 对应说明文字
			List<Account> accountList = Lists.newArrayList(); 
			for (int r = 1; r<=rows; r++) {
				Row row  = sheet.getRow(r);
				if(row==null){
					continue;
				}
				//总列
				int cells = row.getLastCellNum();			
				//账户
				
				
				Account account = new Account();
				//遍历每一列
				for (int col = 0; col<cells; col++) {
					//设置每一列为字符串
					if(row.getCell(col)!=null){
						row.getCell(col).setCellType(Cell.CELL_TYPE_STRING);
					}
				}
				account.setBankcard(row.getCell(0)==null?"":row.getCell(0).toString());
				account.setIdentitycard(row.getCell(1)==null?"":row.getCell(1).toString());
				account.setTelephone(row.getCell(2)==null?"":row.getCell(2).toString());
				account.setLevel(row.getCell(3)==null?"":row.getCell(3).toString());
				account.setScore(row.getCell(4)==null?0:Integer.parseInt(row.getCell(4).getStringCellValue()));
				account.setCorp(new Corporation(corpid));
				accountList.add(account);
			}
			workbook.close();

			/** -------- 处理业务逻辑 -------- */
			//去重复
			Map<String,Account> maps = Maps.newHashMap();
			List<Account> dblist = Lists.newArrayList();			//导入数据
			for (Account account : accountList) {
				maps.put(account.getBankcard(), account);
			}
			
			for (Account account : maps.values()) {
				dblist.add(account);
			}
			logger.info("--> poi read : AccountList size="+dblist.size());
			
			//相同银行卡号更新数据
			for (Account account : dblist) {
				List<Account> accounts =accountDao.findByCorpIdAndBankcard(corpid, account.getBankcard());
				if(accounts.size()>0){
					//更新
					Account entity = accountDao.getOne(accounts.get(0).getId());
					Integer score = account.getScore()+entity.getScore();
					Account temp  = accounts.get(0);
					temp.setScore(score);	//积分
					temp.setLevel(account.getLevel());		//等级
					accountDao.save(temp);
				}else{
					//保存
					accountDao.save(account);
				}
			}
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
	}

	/**
	 * 导出Excel 文件
	 * @return
	 */
	@Override
	public HSSFWorkbook  exportFile(Long corpId) {
		
			
			HSSFWorkbook wb = new HSSFWorkbook();    
	        HSSFSheet sheet = wb.createSheet("Account");    
	        HSSFRow row = sheet.createRow((int) 0);    
	        List<Account> accounts=accountDao.findByCorpId(corpId);
	        
	        String[] names = new String[5];
	        names[0] = "银行卡号                           ";
	        names[1] = "身份证卡号                       ";
	        names[2] = "手机号                     ";
	        names[3] = "等级             ";
	        names[4] = "积分             ";
	       
	        //首行
	        for (int i = 0; i < names.length; i++) {
	        	HSSFCell cell = row.createCell(i);    
	            cell.setCellValue(names[i]);    
	            sheet.autoSizeColumn(i);    
			}
	        //遍历数据库数据
	        for (int i = 0; i < accounts.size(); i++) {  
	        	
	            row = sheet.createRow(i + 1);    
	            row.createCell(0).setCellValue(accounts.get(i).getBankcard());    
	            row.createCell(1).setCellValue(accounts.get(i).getIdentitycard());    
	            row.createCell(2).setCellValue(accounts.get(i).getTelephone());    
	            row.createCell(3).setCellValue(accounts.get(i).getLevel());  
	            row.createCell(4).setCellValue(accounts.get(i).getScore());    
	      
	        }    
	      
	      
		return wb;
	}
	
	/** 绑定银行账户 */
	public ResultObject bindBankcard(Long corpid,Long memberid,String bankcard,String identitycard,String telephone) throws Exception {
		Membership membership = membershipDao.findByMemberIdAndCorpId(memberid, corpid);
		if(membership.getAccount()!=null){
			return new ResultObject("500","您已绑定过银行账户", "");
		}
		Account account = accountDao.findByCorpIdAndBankcardAndIdentitycardAndTelephone(corpid, bankcard, identitycard, telephone);
		if (account==null) {
			return new ResultObject("510", "请检查你输入的信息", "");
		}
		//更新会员身份
		membership.setAccount(account);
		membershipDao.save(membership);
		return new ResultObject("000","绑定银行账户成功", "");
	}
	
	
	/** 通过memberid corpid查询银行账户 */
	public Account getAccountByMemberIdAndCorpId(Long memberid,Long corpid) throws Exception{
		Membership membership = membershipDao.findByMemberIdAndCorpId(memberid, corpid);
		return membership.getAccount();
	}
}
